import { ReactElement, useEffect, useState } from 'react'
import { Skeleton, Radio } from 'antd'
import style from './index.module.less'
import Item from './item'
import { getDataRequest, ItemSchema } from './ajax'
import { ConditionSchema } from '@src/components/schema/condition'
import * as echarts from 'echarts/core'
import { PieChart, PieSeriesOption } from 'echarts/charts'
import { TitleComponent, TitleComponentOption, GridComponent, GridComponentOption, TooltipComponent, ToolboxComponentOption, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { awaitWrap } from '@src/assets/js/tool'
import { getSearch } from '@js/tool'
import qs from 'query-string'
import { Dispatch } from 'redux'
import { useDispatch } from 'react-redux'
import { addWindow } from '@src/redux/actions/tab'
type ECOption = echarts.ComposeOption<PieSeriesOption | TitleComponentOption | GridComponentOption | ToolboxComponentOption>
echarts.use(
  [TitleComponent, TooltipComponent, GridComponent, LegendComponent, PieChart, CanvasRenderer]
)

function getUnit (value: number, dataType: string): { value: number, unit: string } {
  const o: { value: number, unit: string } = { value, unit: '件' }
  if (dataType !== '案件数') {
    if (value > 100000000) {
      o.value = Math.ceil(value / 1000000) / 100
      o.unit = '亿元'
    } else if (value > 10000) {
      o.value = Math.ceil(value / 100) / 100
      o.unit = '万元'
    } else {
      o.value = Math.ceil(value * 100) / 100
      o.unit = '元'
    }
  }
  return o
}

function getOption (data: ItemSchema[], dataType: string): ECOption {
  const total = data.length > 0 ? data.map(li => ({ value: li.value })).reduce((a, b) => ({ value: a.value + b.value })) : { value: 0 }
  const { value, unit } = getUnit(total.value, dataType)
  return {
    tooltip: {
      trigger: 'item',
      formatter: (args: { percent: number, name: string, data: { value: number } }) => {
        const o = getUnit(args.data.value, dataType)
        return `${args.name}：${o.value}${o.unit}（${args.percent}%）`
      },
      position: function (point: number[]) {
        // 固定在顶部
        return [point[0] + 10, point[1] + 10]
      }
    },
    legend: {
      show: false
    },
    series: [
      {
        name: '抽查',
        type: 'pie',
        radius: ['65%', '90%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderWidth: 5,
          borderType: 'solid',
          borderColor: 'rgba(255, 255, 255, 1)'
        },
        minAngle: 4,
        label: {
          show: true,
          position: 'center',
          formatter: `{a|${dataType}}\n{b|${value}${unit}}`,
          backgroundColor: '#fff',
          rich: {
            a: {
              color: '#7E889C',
              lineHeight: 20,
              fontSize: 16
            },
            b: {
              color: '#1F2229',
              lineHeight: 40,
              fontSize: 24
            }
          }
        },
        data: data.map((li, i) => {
          return {
            value: li.value,
            name: li.name,
            itemStyle: { color: li.color }
          }
        })
      }
    ]
  }
}

async function initData (condition: ConditionSchema[], dataType: string, setData: (v: ItemSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getDataRequest(condition, dataType))
  setLoading(false)
  if (e === null && d instanceof Array) {
    setData(d)
  }
}

// 前往案件列表
function toList (name: string, params: {[k: string]: any}, dispatch: Dispatch): void {
  if (name !== '其他') {
    const o = {...params}
    o.closure_type = name
    dispatch(addWindow({ id: 'case-input-list', title: '案件录入', componentName: 'MenuCaseInput', meta: { params: o }, forceRefresh: true }))
  }
}

interface Props {
  condition: ConditionSchema[]
  params: {[k: string]: any}
}

function Main ({ condition, params }: Props): ReactElement {
  const dispatch = useDispatch()
  const [loading, setLoading] = useState(true)
  const [chart, setChart] = useState<echarts.ECharts | null>(null)
  const [data, setData] = useState<ItemSchema[]>([])
  const [dataType, setDataType] = useState('案件数')
  useEffect(() => {
    if (chart === null) {
      const dom: HTMLElement | null = document.querySelector(`.${style.chart}`)
      if (dom !== null) {
        const c = echarts.init(dom)
        setChart(c)
        c.on('click', function (param) {
          toList(param.name, params, dispatch)
        })
      }
    }
  }, [loading])
  useEffect(() => {
    function resize (d: echarts.ECharts): void { d.resize() }
    if (chart !== null) {
      const fs = resize.bind(undefined, chart)
      window.addEventListener('resize', fs)
      return () => {
        window.removeEventListener('resize', fs)
      }
    }
  }, [chart])
  useEffect(() => {
    initData(condition, dataType, setData, setLoading).catch(e => console.error(e))
  }, [condition, dataType])
  useEffect(() => {
    if (chart !== null && !loading) {
      chart.setOption(getOption(data, dataType))
    }
  }, [chart, loading, data])
  return (
    <div className={style.container}>
      <div className={style.header}>
        <span className={style['header-title']}>结案方式</span>
        <Radio.Group value={dataType} onChange={v => setDataType(v.target.value)}>
          <Radio.Button value='案件数'>案件数</Radio.Button>
          <Radio.Button value='总标的'>总标的</Radio.Button>
          <Radio.Button value='本请求'>本请求</Radio.Button>
          <Radio.Button value='反请求'>反请求</Radio.Button>
        </Radio.Group>
      </div>
      <div className={style.body}>
        <Skeleton active loading={loading}>
          <div className={style.chart}></div>
          <div className={style['list-box']}>
            <ul className={style.list}>
              {data.map((li, i) => {
                const o = getUnit(li.value, dataType)
                return <Item key={i} {...li} value={o.value} unit={o.unit} />
              })}
            </ul>
          </div>
        </Skeleton>
      </div>
    </div>
  )
}

export default Main
